﻿using System;
using System.Globalization;

namespace CustomerContactSystem.WebForms.Admin.Categories
{
    public partial class Edit : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsValidPageRequest(true, true, "id")) {
                return;
            }
            GetDepartments();
            GetCategory();
        }

        private void GetDepartments() {
            var departments = DepartmentRepository.QueryOver().OrderBy(d => d.DepartmentName).Asc.List();
            BindDropDownList(DepartmentList, departments, "DepartmentName", "Id", "--Select--", "0");
        }

        private void GetCategory() {
            var categoryId = int.Parse(Request.QueryString["id"]);
            var category = EnquiryCategoryRepository.GetById(categoryId);

            if (category == null) {
                return;
            }

            DepartmentList.SelectedIndex =
                DepartmentList.Items.IndexOf(
                    DepartmentList.Items.FindByValue(
                    category.Department.Id.ToString(CultureInfo.InvariantCulture)));
            CategoryName.Text = category.CategoryName;
            AvailableForSelection.Checked = category.AvailableForSelection;
        }

        protected void SaveCategoryClick(object sender, EventArgs e)
        {
            if (!IsValidPageRequest(true, false, "id")) {
                return;
            }

            var categoryId = int.Parse(Request.QueryString["id"]);
            var category = EnquiryCategoryRepository.GetById(categoryId);
            category.Department = DepartmentRepository.LoadReference(int.Parse(DepartmentList.SelectedItem.Value));
            category.CategoryName = CategoryName.Text;
            category.AvailableForSelection = AvailableForSelection.Checked;

            if (!IsValidObject(category, ErrorMsg))
            {
                return;
            }

            EnquiryCategoryRepository.Update(category);
            Response.Redirect("~/Admin/Categories/List.aspx#" + category.Id);
        }
    }
}